﻿using System;
using System.Xml;

namespace Moonlite.Data.EditorInterop
{
    public class ObjectsDeserializer : IDeserializer
    {
        public DeserializedObjectCollection BuildTree(string rawInputData)
        {
            DeserializedObjectCollection objects = new DeserializedObjectCollection();
            XmlDocument document = new XmlDocument();
            document.LoadXml(rawInputData);
            foreach (XmlNode node in document.ChildNodes)
            {
                if (node.Name.ToLower() == "placedobjects")
                {
                    int version = 0;
                    foreach (XmlAttribute attribute in node.Attributes)
                    {
                        if (attribute.Name.ToLower() == "version")
                        {
                            version = int.Parse(attribute.Value);
                        }
                    }

                    PlacedObjects placedObjects = new PlacedObjects(version);
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        switch (childNode.Name.ToLower())
                        {
                            case "unit":
                            case "objectunit":
                                placedObjects.Children.Add(ObjectUnit.Parse(childNode));
                                break;
                            case "doodad":
                            case "objectdoodad":
                                placedObjects.Children.Add(ObjectDoodad.Parse(childNode));
                                break;
                            case "point":
                            case "objectpoint":
                                placedObjects.Children.Add(ObjectPoint.Parse(childNode));
                                break;
                            case "camera":
                            case "objectcamera":
                                placedObjects.Children.Add(ObjectCamera.Parse(childNode));
                                break;
                        }
                    }

                    objects.Add(placedObjects);
                }
            }

            return objects;
        }
    }
}
